package logic

import (
	"whale/internal/app/admin/consts/req"
	"whale/internal/app/admin/consts/res"
	"whale/internal/app/admin/errors"
	"whale/internal/app/admin/model"
	"whale/internal/repository"
	"whale/pkg/utils"
)

// logic *BannerLogic IBannerLogic
type IBannerLogic interface {
	// 广告列表
	GetList(data req.BannerListReq) (interface{}, error)
	// 广告详情
	GetInfo(id int) (interface{}, error)
	// 创建广告
	Create(data req.BannerCreatreReq) error
	// 更新广告
	Update(data req.BannerUpdateReq) error
	// 删除广告
	Deleted(id int) error
	// 更新信息
	Set(data req.SetDataReq) error
}

// 广告列表
func (logic *BannerLogic) GetList(data req.BannerListReq) (interface{}, error) {
	var list []res.BannerListRes

	if err := logic.Repository.Table(&model.Banner{}).Where("key = ?", data.Key).Paging(data.Page, data.PageSize).GetList(&list); err != nil {
		return nil, errors.DBReadError()
	}
	return list, nil
}

// 广告详情
func (logic *BannerLogic) GetInfo(id int) (interface{}, error) {
	var info res.BannerInfoRes

	if _, err := logic.Repository.Table(&model.Banner{}).Where("id = ?", id).Get(&info); err != nil {
		return nil, errors.DBReadError()
	}
	return info, nil
}

// 创建广告
func (logic *BannerLogic) Create(data req.BannerCreatreReq) error {
	var bannerData model.Banner

	if err := utils.StructCopy(&bannerData, &data); err != nil {
		return errors.DataLegalError()
	}

	return logic.Repository.Table(&model.Banner{}).Insert(&bannerData)
}

// 更新广告
func (logic *BannerLogic) Update(data req.BannerUpdateReq) error {
	var bannerData model.Banner

	if err := utils.StructCopy(&bannerData, &data); err != nil {
		return errors.DataLegalError()
	}

	return logic.Repository.Table(&model.Banner{}).Where("id = ?", data.Id).Update(&bannerData)
}

// 更新信息
func (logic *BannerLogic) Set(data req.SetDataReq) error {
	if utils.ContainsKeyInSlice(data.Value, []string{"status", "sort"}) {
		return errors.DataLegalError()
	}
	return logic.Repository.Table(&model.Banner{}).Where("id = ?", data.Id).Update(data.Value)
}

// 删除广告
func (logic *BannerLogic) Deleted(id int) error {
	return logic.Repository.Table(&model.Banner{}).Where("id = ?", id).Deleted()
}

type BannerLogic struct {
	Repository repository.IRepository `bean:"Repository"`
}
